// let API_URL = "https://miniapp.jzhlife.com/";
let API_URL = "https://sincer.icbc.nervenets.cn/";

function getDomain() {
	return API_URL;
}
//计算距离
function distance(location,lat2,lng2){
	if(!location.lat){
		return false
	}
	let lat1=location.lat,
		lng1=location.lng;
	let radLat1 =lat1 * Math.PI / 180.0
	let radLat2 =lat2 * Math.PI / 180.0
	let a = radLat1 - radLat2;
	let  b =lng1 * Math.PI / 180.0-lng2 * Math.PI / 180.0
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
		Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
	s = s *6378.137 ;// EARTH_RADIUS;
	s = Math.round(s * 100) / 100; //输出为公里
	return s
}
function getApiUrl() {
	return this.getDomain() + "api/v1/"
}

function fmoney(s, n) {

	n = n > 0 && n <= 20 ? n : 2;

	s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";

	var l = s.split(".")[0].split("").reverse(),
		r = s.split(".")[1];

	var t = "";

	for (var i = 0; i < l.length; i++) {

		t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");

	}

	return t.split("").reverse().join("") + "." + r;

}
// function formatTime(time) {
// 	if (typeof time !== 'number' || time < 0) {
// 		return time
// 	}
//
// 	var hour = parseInt(time / 3600)
// 	time = time % 3600
// 	var minute = parseInt(time / 60)
// 	time = time % 60
// 	var second = time
//
// 	return ([hour, minute, second]).map(function(n) {
// 		n = n.toString()
// 		return n[1] ? n : '0' + n
// 	}).join(':')
// }

function timestampToFormatString(timstamp, format) {
	if (!format) format = "yyyy-MM-dd hh:mm:ss";
	let newDate = new Date();
	newDate.setTime(timstamp * 1000);
	return newDate.format(format)
}

function parseTime(time, cFormat) {
	if (arguments.length === 0) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if (('' + time).length === 10) time = parseInt(time) * 1000
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

function formatTime(time, option) {
	time = +time * 1000
	const d = new Date(time)
	const now = Date.now()

	const diff = (now - d) / 1000

	if (diff < 30) {
		return '刚刚'
	} else if (diff < 3600) {
		// less 1 hour
		return Math.ceil(diff / 60) + '分钟前'
	} else if (diff < 3600 * 24) {
		return Math.ceil(diff / 3600) + '小时前'
	} else if (diff < 3600 * 24 * 2) {
		return '1天前'
	}
	if (option) {
		return parseTime(time, option)
	} else {
		return (
			d.getMonth() +
			1 +
			'月' +
			d.getDate() +
			'日' +
			d.getHours() +
			'时' +
			d.getMinutes() +
			'分'
		)
	}
}


function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

Date.prototype.format = function(format) {
	var args = {
		"M+": this.getMonth() + 1,
		"d+": this.getDate(),
		"h+": this.getHours(),
		"m+": this.getMinutes(),
		"s+": this.getSeconds(),
		"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
		"S": this.getMilliseconds()
	};
	if (/(y+)/.test(format))
		format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var i in args) {
		var n = args[i];
		if (new RegExp("(" + i + ")").test(format))
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length));
	}
	return format;
};

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};
//展示整数变小数
function showDecimal(num, fixed) {
	let numObj = parseFloat(num / 100);
	return parseFloat(numObj.toFixed(fixed || 2));
}

//展示小数变整数
function toInteger(num) {
    let  numObj = parseFloat(num);
    return parseInt((numObj * 100).toFixed(2));
}

function isMobile(str) {
	let myreg = /^[1][3-9][0-9]{9}$/;
	if (!myreg.test(str)) {
		return false;
	} else {
		return true;
	}
}

function isCardNo(card) {
	// 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
	// var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
	var reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/;
	if (!reg.test(card)) {
		return false;
	} else {
		return true;
	}
}

function getUserToken() {
	return uni.getStorageSync('token');
}



function ajax(method, data, success, fail) {
	uni.showLoading({
		title: '加载中'
	});
	uni.request({
		url: this.getApiUrl() + method,
		data: data,
		method: 'POST',
		header: {
			'content-type': 'application/json' //自定义请求头信息
		},
		success: (res) => {
			uni.hideLoading();
			if (200 == res.statusCode && success) success(res);
			else uni.showModal({
				title: '提示',
				content: '网络出错，无法访问服务器，请检查网络再试！',
				success: function(res) {
					if (res.confirm) {
						console.log('用户点击确定');
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		fail: fail,
		complete: () => {
			console.log('complete')
		}
	});
}

module.exports = {
	formatTime: formatTime,
	parseTime: parseTime,
	timestampToFormatString: timestampToFormatString,
	formatLocation: formatLocation,
	showDecimal: showDecimal,
	toInteger: toInteger,
	isMobile: isMobile,
	isCardNo: isCardNo,
	dateUtils: dateUtils,
	ajax: ajax,
	getUserToken: getUserToken,
	getDomain: getDomain,
	getApiUrl: getApiUrl,
	fmoney: fmoney,
	distance:distance
}
